package terra;

import terra.definitions.NpcDef;
import terra.managers.DefManager;
import terra.managers.MapManager;
import terra.managers.ObjectManager;
import terra.model.World;
import terra.model.map.Map;
import terra.model.object.NpcObject;
import terra.model.object.Player;
import terra.network.packet.server.ChatMessage;

public class AdminCommandHandler {

	public static void handleCommand(String s, Player p) {
		String c = s.substring(6);
		String[] com = c.split("_");
		switch (com[0]) {
		case "spawn":
			handleSpawn(com, p);
			break;
		case "save":
			handleSave(com, p);
			break;
		case "pos":
			handlePos(com, p);
			break;
		case "teleport":
			handleTeleport(com, p);
		case "item":
			handleItem(com, p);
			break;
		}
	}

	private static void handleItem(String[] com, Player p) {
		if (com.length == 1)
			return;
		if (com.length == 2){
			int itemId = Integer.parseInt(com[1]);
			p.inv.pickupItem(itemId, 1);
		} else{
			int itemId = Integer.parseInt(com[1]);
			int count = Integer.parseInt(com[2]);
			p.inv.pickupItem(itemId, count);
		}
	}

	private static void handleTeleport(String[] com, Player p) {
		if (com.length  == 1){
			p.setY(0);
		}
	}

	private static void handlePos(String[] com, Player p) {
		p.send(new ChatMessage(-1,"Current position: "+(int)p.getX()+" _ "+(int)p.getY()));
	}

	private static void handleSave(String[] com, Player p) {
		if (com.length == 1) {
			p.getMap().save();
		} else if (com[1].equalsIgnoreCase("all")) {
			for (Map m : MapManager.getInstance().getMaps().values())
				m.save();
			MapManager.getInstance().saveNpcs();
		}
	}

	private static void handleSpawn(String[] com, Player p) {
		if (com.length <=1)
			return;
		if (com[1] == null)
			return;
		int id = Integer.parseInt(com[1]);
		NpcDef def = DefManager.npcDefs.get(id);
		if (def == null)
			return;
		int count = 1;
		if (com.length > 2)
			count = Integer.parseInt(com[2]);
		for (int i = 0; i < count; i++) {
			NpcObject obj = ObjectManager.createNpc(def);
			obj.setX(p.getX());
			obj.setY(p.getY() - 32);
			World.getInstance().addObject(obj.getObjectId(), obj);
		}

	}

}
